<script setup lang="ts">
import type { SaveMessageRequest } from '@/api/webSite/request';
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElNotification } from 'element-plus'

const message = reactive<SaveMessageRequest>({ nickName: "", email: "", body: "", profession: 0 });
//表单实例
const formRef = ref<FormInstance>();

//自定义邮箱验证
const emailValidate = (rule: any, value: string, callback: any) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱地址！'))
  } else {
    callback()
  }
}

//验证规则
const messageRules = reactive<FormRules<SaveMessageRequest>>({
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'change' },
    { min: 3, max: 10, message: '昵称长度不能小于3大于5', trigger: 'change' },
  ],
  email: [
    { required: true, message: '请输入邮件', trigger: 'change' },
    { validator: emailValidate, trigger: 'change' }
  ],
  body: [
    { required: true, message: '请输入留言', trigger: 'change' },
    { min: 10, max: 100, message: '留留言不能少于10多于100个字', trigger: 'change' },
  ],
});

//表单提交
const submit = async (fromElement: FormInstance | null) => {
  await fromElement?.validate((valid, fields) => {
    if (valid) {
      //发送Api请求保存数据

      ElNotification({
        title: '提示',
        message: "提交成功",
        position: 'bottom-right',
      })

      closedialogForm();
    }
  })
}

//关闭表单弹窗
const emit = defineEmits(["closedialogForm"]);
function closedialogForm() {
  emit("closedialogForm", false);
}


const reset = (fromElement: FormInstance | undefined) => {
  if (!fromElement) return
  fromElement.resetFields()
}

</script>

<template>
  <el-form ref="formRef" :rules="messageRules" :model="message" style="max-width: 600px" label-width="auto"
    class="demo-ruleForm" status-icon>
    <el-form-item label="昵称" prop="nickName">
      <el-input v-model="message.nickName" placeholder="请输入你的昵称" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="message.email" placeholder="请输入你的邮箱" />
    </el-form-item>
    <el-form-item label="职业">
      <el-select v-model="message.profession" placeholder="请选择你的职业">
        <el-option label="神秘人" :value="0" />
        <el-option label="开发者" :value="1" />
        <el-option label="学生" :value="2" />
        <el-option label="老师" :value="3" />
      </el-select>
    </el-form-item>
    <el-form-item label="留言" prop="body">
      <el-input v-model="message.body" :rows="5" type="textarea" placeholder="请输入你的留言" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit(formRef)"> 提交</el-button>
      <el-button @click="reset(formRef)">重置</el-button>
    </el-form-item>
  </el-form>

</template>

<style lang="scss" scoped>
:deep(.el-form-item__content) {
  justify-content: flex-end;
}
</style>
